import {setImageSize} from '../../utils/setImageSize.js'
import {getRect} from '../../utils/getRect.js'
import {shareApp} from '../../utils/shareApp.js'
import {addShare, baseUrl, dianZan, getArticleDetail, publishComment, publishReplyComment} from '../../api/index'
import {vModel} from '../../utils/v-model.js'
import {hidePhone} from '../../utils/util'
import {previewImage} from '../../utils/previewImage'
import {getUserInfo} from '../../utils/getUserInfo'
import {getUserLocation, getDistance} from '../../utils/getLocation'
// pages/article/index.js
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: baseUrl,
    articleID: '',
    canSee: false,
    zanLoading: false,
    images: [],
    commentPlaceholder: '',
    commentVisible: false,
    article: {},
    comment: '',
    commentPid: ''
  },
  bindNavToIndex () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // textarea 数据绑定
  bindInput (e) {
    vModel(this, e)
  },
  bindImageLoad (e) {
    setImageSize(this, e.detail, e.target.dataset.index)
  },
  bindClickCommentBtn (e) {
    let _this = this
    let _dataset = e.currentTarget.dataset
    _this.setData({
      handle: _dataset.handle,
      commentPlaceholder: _dataset.handle === 'reply' ? `回复：${_dataset.nickname}` : '请输入内容',
      commentVisible: true
    })
    if (_dataset.pid) {
      _this.setData({
        commentPid: _dataset.pid,
      })
    }
    getRect('#js-page-detail', (rect) => {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 0
      })
    })
  },
  // onClosePopup
  onClosePopup () {
    this.setData({
      commentVisible: false
    })
  },
  // 获取回复对象昵称
  getReplyListNickName (commentList) {
    if (!commentList.length) return
    if (commentList.length) {
      commentList = commentList.map(item => {
        if (item.reply && item.reply.length) {
          // 获取所有参与人员昵称
          let _nicknameMaps = {}
          item.reply.forEach(replyItem => {
            _nicknameMaps[replyItem.id] = replyItem.nickname
          })
          // 通过pid 获取被回复用户的昵称
          item.reply = item.reply.map(rItem => {
            if (_nicknameMaps[rItem.id]) {
              rItem._p_nickname = _nicknameMaps[rItem.pid]
            }
            return rItem
          })
        }
      })
    }
  },
  openLocation () {
    let _article = this.data.article
    wx.getLocation({
      success (res) {
        wx.setStorageSync('user_location_x', res.latitude)
        wx.setStorageSync('user_location_y', res.longitude)
        _this.showDistance(res.latitude, res.longitude)
      }
    })
    wx.openLocation({
      latitude: parseFloat(_article.position_x) || 0,
      longitude: parseFloat(_article.position_y) || 0,
    })
    // getUserLocation().then(res => {
    //   let distance = getDistance(res.latitude, res.longitude, res.latitude, res.longitude, )
    // })
  },
  showDistance (x, y) {
    let userX = wx.getStorageSync('user_location_x')
    let userY = wx.getStorageSync('user_location_y')
    let _distance = getDistance(x, y, userX, userY)
    this.setData({
      distance: _distance >= 1000 ? ((_distance / 1000).toFixed(1) + '公里') : (_distance + '米')
    })
  },
  // 获取详情
  getDetail () {
    let _this = this
    let id = _this.data.articleID
    wx.showNavigationBarLoading()
    getArticleDetail({id}).then(res => {
      let _info = res.data.info
      let _comment = _info.comment_list
      if (_comment) {
        _info._comment_list = Object.keys(_comment).map(key => ({cid: key, ..._comment[key]}))
        _this.getReplyListNickName(_info._comment_list)
      }
      if (_info.mine < 1) {
        _info.bg_phone = hidePhone(_info.bg_phone)
        _info.bg_sender_name = hidePhone(_info.bg_sender_name)
        _info.bg_geter_name = hidePhone(_info.bg_geter_name)
      }
      this.showDistance(_info.position_x, _info.position_y)
      _this.setData({
        articleID: id,
        article: _info,
        canSee: true
      })
      wx.hideNavigationBarLoading()
    }).catch(err => {
      console.log('error, err', err)
      wx.showToast({
        icon: 'none',
        title: err.data.info,
        duration: 3000
      })
      setTimeout(() => {
        console.log('navigateBack')
        wx.navigateBack()
      }, 3000)
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 3500)
    })
  },
  
  bindPreviewImage (e) {
    let _dataset = e.currentTarget.dataset
    console.log(_dataset)
    previewImage(baseUrl + _dataset.src, _dataset.urls.map((item) => baseUrl + item))
  },
  
  // 评论
  bindPublishComment () {
    getUserInfo(true).then(res => {
      if (this.data.handle === 'reply') {
        this.sendReply()
      } else {
        this.sendComment()
      }
    })
  },
  // 清除内容
  bindClearCommentText () {
    this.setData({
      comment: ''
    })
  },
  
  // 发表评论
  sendComment () {
    let _this = this
    let _data = _this.data
    console.log(_data.comment)
    if (_data.comment.trim() === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入评论内容~'
      })
      return
    }
    wx.showLoading({
      title: '加载中..'
    })
    publishComment({
      aid: _data.articleID,
      content: _data.comment
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '发表成功'
      })
      this.setData({
        commentVisible: false,
        comment: ''
      })
      _this.getDetail()
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        icon: 'none',
        title: err.data.info
      })
    })
  },
  
  // 回复评论
  sendReply () {
    let _this = this
    let _data = _this.data
    console.log(_data.comment)
    if (_data.comment.trim() === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入内容~'
      })
      return
    }
    wx.showLoading({
      title: '加载中..'
    })
    publishReplyComment({
      aid: _data.articleID,
      content: _data.comment,
      pid: _data.commentPid
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '发表成功'
      })
      _this.setData({
        commentVisible: false,
        comment: ''
      })
      _this.getDetail()
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.info
      })
    })
  },
  // 点赞
  bindZan () {
    let _this = this
    let _data = _this.data
    // 防止多次请求
    if (_data.zanLoading) return
    _this.setData({
      zanLoading: true
    })
    dianZan({aid: _data.articleID}).then(res => {
      let _isZan = res.data.status === 1
      let _picks = _data.article.picks
      _this.setData({
        'article.picks': _isZan ? (_picks - 0 + 1) : _picks - 1,
        'article.is_pick': _isZan ? 1 : 0,
        zanLoading: false
      })
    }).catch(err => {
      wx.showToast({
        icon: 'none',
        title: err.data && err.data.info
      })
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({id}) {
    this.setData({
      articleID: id
    }, () => {
      this.getDetail()
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('onReady')
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onShow')
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    let _articleID = this.data.articleID
    return shareApp('/pages/article/index?id=' + _articleID)
  }
})
